package com.yun.newBlog.blog.social;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

/**
 * qq接口实现类
 */
@Slf4j
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ{

    // 获取登录用户的openId的url
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    // 从QQ中获取用户信息的url
    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;
    private String openId;
    private ObjectMapper objectMapper =new ObjectMapper();

    public QQImpl(String accessToken,String appId){

        //access_token作为查询参数来携带。
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);

        this.appId =appId; // 第三方应用id

        // 获取用户的openId
        String url = String.format(URL_GET_OPENID, accessToken);
        String result = getRestTemplate().getForObject(url, String.class);

        log.info("【QQImpl】 QQ_URL_GET_OPENID={} result={}", URL_GET_OPENID, result);

        this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
    }

    @Override
    public QQUserInfo getUserInfo(){
        String url = String.format(URL_GET_USERINFO, appId,openId);
        String result = getRestTemplate().getForObject(url, String.class);
        QQUserInfo qqUserInfo = new QQUserInfo();
        try {
            qqUserInfo = objectMapper.readValue(result, QQUserInfo.class);//将字符串转换为对象
        } catch (Exception e) {
            throw new RuntimeException("获取用户信息失败",e);
        }
        log.info("QQImpl 获取用户信息："+qqUserInfo);
        return qqUserInfo;
    }
}